package com.lrkj.waitress.service.impl;

import com.lrkj.common.constant.UserConstants;
import com.lrkj.common.core.domain.entity.OrgTree;
import com.lrkj.common.core.domain.entity.SysUser;
import com.lrkj.common.exception.BaseException;
import com.lrkj.common.exception.CustomException;
import com.lrkj.common.utils.DateUtils;
import com.lrkj.common.utils.IdcardUtil;
import com.lrkj.common.utils.SecurityUtils;
import com.lrkj.common.utils.StringUtils;
import com.lrkj.common.utils.uuid.IdUtils;
import com.lrkj.property.domain.Community;
import com.lrkj.property.domain.Room;
import com.lrkj.property.service.ICommunityService;
import com.lrkj.property.service.IRoomService;
import com.lrkj.system.mapper.OrgTreeMapper;
import com.lrkj.waitress.domain.CustomInfo;
import com.lrkj.waitress.mapper.CustomInfoMapper;
import com.lrkj.waitress.service.ICustomInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 客户管理Service业务层处理
 *
 * @author yajun_ren
 * @date 2022-03-17
 */
@Service
public class CustomInfoServiceImpl implements ICustomInfoService {
    @Autowired
    private CustomInfoMapper customInfoMapper;

    @Autowired
    private ICommunityService communityService;

    @Autowired
    private IRoomService roomService;

    @Autowired
    private OrgTreeMapper orgTreeMapper;


    /**
     * 查询客户管理
     *
     * @param customId 客户管理ID
     * @return 客户管理
     */
    @Override
    public CustomInfo selectCustomInfoById(String customId) {
        return customInfoMapper.selectCustomInfoById(customId);
    }

    /**
     * 查询客户管理列表
     *
     * @param customInfo 客户管理
     * @return 客户管理
     */
    @Override
    public List<CustomInfo> selectCustomInfoList(CustomInfo customInfo) {
        return customInfoMapper.selectCustomInfoList(customInfo);
    }

    @Override
    public CustomInfo getWxUserCustomInfo(String communityId, String cellPhoneNumber) {
        CustomInfo ciEg = new CustomInfo();
        ciEg.setCellPhoneNumber(cellPhoneNumber);//手机号码
        ciEg.setCommunityId(communityId);//小区ID
        //默认是  手机号码+小区ID 唯一
        List<CustomInfo> customInfos = selectCustomInfoList(ciEg);
        if (customInfos.size() > 0) {
            return customInfos.get(0);
        }
        return null;
    }

    /**
     * 新增客户管理
     *
     * @param customInfo 客户管理
     * @return 结果
     */
    @Override
    public int insertCustomInfo(CustomInfo customInfo) {
        if(StringUtils.isEmpty(customInfo.getCustomId())){
            customInfo.setCustomId(IdUtils.simpleUUID());
        }
        customInfo.setCreateTime(DateUtils.getNowDate());
        try {
            customInfo.setCreateBy(SecurityUtils.getUsername());
        } catch (Exception e) {
        }
        customInfo.setCustomNo(IdUtils.generateId() + "");//客户号
        this.setInfo(customInfo);
        return customInfoMapper.insertCustomInfo(customInfo);
    }

    /**
     * 修改客户管理
     *
     * @param customInfo 客户管理
     * @return 结果
     */
    @Override
    public int updateCustomInfo(CustomInfo customInfo) {
        customInfo.setUpdateTime(DateUtils.getNowDate());
        customInfo.setUpdateBy(SecurityUtils.getUsername());
        this.setInfo(customInfo);
        //更新组织树  业主信息
        Room eg = new Room();
        eg.setOwnerId(customInfo.getCustomId());
        List<Room> rooms = roomService.selectRoomList(eg);
        rooms.stream().forEach(room -> {
            OrgTree orgTree = orgTreeMapper.selectOrgTreeById(room.getId());
            if (null != orgTree) {
                orgTree.setOwnerName(customInfo.getCustomName());
                orgTreeMapper.updateOrgTree(orgTree);
            }
        });
        return customInfoMapper.updateCustomInfo(customInfo);
    }

    private void setInfo(CustomInfo customInfo) {
        Community community = communityService.selectCommunityById(customInfo.getCommunityId());
        customInfo.setDeptId(community.getDeptId());
        customInfo.setAncestors(community.getAncestors() + "," + community.getId());
    }

    /**
     * 批量删除客户管理
     *
     * @param customIds 需要删除的客户管理ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteCustomInfoByIds(String[] customIds) {
        for (int i = 0; i < customIds.length; i++) {
            Room room= new Room();
            room.setOwnerId(customIds[i]);
            List<Room> roomList = roomService.selectRoomList(room);
            CustomInfo customInfo = customInfoMapper.selectCustomInfoById(customIds[i]);
            if (roomList.size()>0){
                throw new BaseException(String.format("客户:%s已绑定房屋，请先删除", customInfo.getCustomName()));
            }
        }

        return customInfoMapper.deleteCustomInfoByIds(customIds);
    }

    /**
     * 删除客户管理信息
     *
     * @param customId 客户管理ID
     * @return 结果
     */
    @Override
    public int deleteCustomInfoById(String customId) {
        Room room= new Room();
        room.setOwnerId(customId);
        List<Room> roomList = roomService.selectRoomList(room);
        CustomInfo customInfo = customInfoMapper.selectCustomInfoById(customId);
        if (roomList.size()>0){
            throw new BaseException(String.format("客户:%s已绑定房屋，请先删除", customInfo.getCustomName()));
        }

        return customInfoMapper.deleteCustomInfoById(customId);
    }

    /**
     * 批量新增客户管理信息
     *
     * @param customInfos 客户管理对象
     */
    public int batchAddData(List<CustomInfo> customInfos) {
        return customInfoMapper.batchAddData(customInfos);
    }


    /**
     * 校验code是否唯一
     *
     * @param bean
     * @return
     */
    @Override
    public String checkCodeUnique(CustomInfo bean) {
        String status = UserConstants.UNIQUE;
        CustomInfo eg = new CustomInfo();
        eg.setCustomName(bean.getCustomName());
        eg.setCommunityId(bean.getCommunityId());
        List<CustomInfo> customInfos = customInfoMapper.selectCustomInfoList(eg);
        //修改
        if (StringUtils.isNotEmpty(bean.getCustomId())) {
            if (null != customInfos && customInfos.size() > 0) {
                CustomInfo info = customInfos.get(0);
                if (!bean.getCustomId().equals(info.getCustomId())) {
                    status = UserConstants.NOT_UNIQUE;
                }
            }
        } else {
            //新增
            if (null != customInfos && customInfos.size() > 0) {
                status = UserConstants.NOT_UNIQUE;
            }
        }
        return status;
    }

    @Override
    public int updateCustomPhone(CustomInfo customInfo) {
        return customInfoMapper.updateCustomPhone(customInfo);
    }

    @Override
    public String importData(List<CustomInfo> beanList, String currencyCommunityId) {

        if (StringUtils.isNull(beanList) || beanList.size() == 0) {
            throw new CustomException("导入客户信息数据不能为空！");
        }
        if (StringUtils.isNull(currencyCommunityId)) {
            throw new CustomException("还没有关联小区,请先关联小区！");
        }
        //新增客户列表
        List<CustomInfo> savaList = new ArrayList<>();
        //更新客户列表
        List<CustomInfo> updateList = new ArrayList<>();

        Community community = communityService.selectCommunityById(currencyCommunityId);

        CustomInfo eg = new CustomInfo();
        eg.setCommunityId(currencyCommunityId);
        List<CustomInfo> customInfos = customInfoMapper.selectCustomInfoList(eg);
        Map<String, CustomInfo> customInfoMap = customInfos.stream().collect(Collectors.toMap(k -> k.getCustomName() + k.getCellPhoneNumber(), CustomInfo -> CustomInfo));

        SysUser user = SecurityUtils.getLoginUser().getUser();

        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();

        for (CustomInfo bean : beanList) {
            CustomInfo savaBean = new CustomInfo();
            successNum++;
            try {
                if (StringUtils.isNull(bean.getCustomName())) {
                    successMsg.append("<br/>" + successNum + "导入失败,客户名称不能为空!");
                    continue;
                }
                if (StringUtils.isNull(bean.getCellPhoneNumber())) {
                    successMsg.append("<br/>" + successNum + "导入失败,手机号不能为空!");
                    continue;
                }

                if (StringUtils.isNull(bean.getCustomType())) {
                    successMsg.append("<br/>" + successNum + "导入失败,客户类别不能为空!");
                    continue;
                }

                if (StringUtils.isNotEmpty(bean.getIdCard()) && !IdcardUtil.isValidatedAllIdcard(bean.getIdCard())) {
                    successMsg.append("<br/>" + successNum + "、导入失败,不是有效的证件号码!");
                    continue;
                }

                //客户唯一编号
                String customInfoKey = bean.getCustomName() + bean.getCellPhoneNumber();
                if (customInfoMap.containsKey(customInfoKey)) {
                    //修改
                    CustomInfo oldCustomInfo = customInfoMap.get(customInfoKey);
                    oldCustomInfo.setCellPhoneNumber(bean.getCellPhoneNumber());
                    oldCustomInfo.setCustomType(bean.getCustomType());
                    oldCustomInfo.setLinkman(bean.getLinkman());
                    oldCustomInfo.setContactAddress(bean.getContactAddress());
                    oldCustomInfo.setIdCard(bean.getIdCard());
                    oldCustomInfo.setCorporateName(bean.getCorporateName());
                    oldCustomInfo.setUpdateBy(user.getNickName());
                    oldCustomInfo.setUpdateTime(DateUtils.getNowDate());
                    oldCustomInfo.setCustomHeadImg(bean.getCustomHeadImg());
                    updateList.add(oldCustomInfo);
                    successMsg.append("<br/>" + successNum + "、客户信息 " + oldCustomInfo.getCustomName() + " 更新成功");
                } else {
                    savaBean.setCustomId(IdUtils.simpleUUID());
                    savaBean.setCustomName(bean.getCustomName());
                    savaBean.setCellPhoneNumber(bean.getCellPhoneNumber());
                    savaBean.setIdCard(bean.getIdCard());
                    savaBean.setCorporateName(bean.getCorporateName());
                    savaBean.setCustomType(bean.getCustomType());
                    savaBean.setLinkman(bean.getLinkman());
                    savaBean.setContactAddress(bean.getContactAddress());
                    savaBean.setCommunityId(community.getId());
                    savaBean.setDeptId(community.getDeptId());
                    savaBean.setAncestors(community.getAncestors() + "," + community.getId());
                    savaBean.setCreateBy(user.getNickName());
                    savaBean.setCreateTime(DateUtils.getNowDate());
                    savaBean.setSex(IdcardUtil.getGenderByIdCard(bean.getIdCard()));
                    savaBean.setBirthDate(IdcardUtil.getIdCardBirthday(bean.getIdCard()));
                    savaBean.setCustomHeadImg(bean.getCustomHeadImg());
                    savaList.add(savaBean);
                    successMsg.append("<br/>" + successNum + "、客户信息 " + savaBean.getCustomName() + " 导入成功");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、客户信息 " + bean.getCustomName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
            }
        }
        this.doSaveList(savaList);
        this.doUpdateList(updateList);
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new CustomException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    @Override
    public int updateAppUserId(CustomInfo customInfo) {
        return customInfoMapper.updateAppUserId(customInfo);
    }


    public int doUpdateList(List<CustomInfo> batchBean) {
        List<CustomInfo> updateBeans = new ArrayList<>();
        //数据同步单次新增条数
        Integer maxNum = 500;
        if (batchBean.size() > maxNum) {
            for (int i = 0; i < batchBean.size(); i++) {
                if ((i + 1) % maxNum == 0) {
                    updateBeans.add(batchBean.get(i));
                    customInfoMapper.batchUpdate(updateBeans);
                    updateBeans.clear();
                } else {
                    updateBeans.add(batchBean.get(i));
                }
            }
            if (null != updateBeans && updateBeans.size() > 0) {
                customInfoMapper.batchUpdate(updateBeans);
            }
        } else {
            if (batchBean.size() > 0) {
                customInfoMapper.batchUpdate(batchBean);
            }
        }
        return 1;
    }


}
